#include "KDM1EventAction.hh"
#include "KDM1HitsCollection.hh"
#include "KDM1Hit.hh"
#include "KDM1Globals.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4ThreeVector.hh"
#include "TH3D.h"
#include "TFile.h"
#include <sstream>

KDM1EventAction::KDM1EventAction()
{
	;
}

KDM1EventAction::~KDM1EventAction(){;}

void KDM1EventAction::BeginOfEventAction(const G4Event*)
{
	;
}

void KDM1EventAction::EndOfEventAction(const G4Event* event)
{
	G4HCofThisEvent* hcc = event->GetHCofThisEvent();
	KDM1HitsCollection* hc = (KDM1HitsCollection*)(hcc->GetHC(0));

	size_t size = hc->GetSize();

	int kaonNumber = eventNum/3;
	int pionNumber = eventNum%3;
	std::stringstream ss;
	ss << "kaonNumber" << kaonNumber;
	G4String name = ss.str();
	if(pionNumber == 0)
	{
		tree = new TTree(name,"Kaon");
		TBranch* energyBranch = tree->Branch("energy",&(energyList[kaonNumber]),"energy/D");
		energyBranch->Fill();
	}
	std::stringstream ss2;
	ss2 << "pionNumber" << pionNumber;
	name = ss2.str();
	dataForm* data = new dataForm;
	TBranch* branch = tree->Branch(name,&(*data).energy,"energy/D:time:x:y:z");
	for(size_t i = 0;i < size;i++)
	{
		KDM1Hit* hit = (KDM1Hit*)hc->GetHit(i);
		(*data).energy = hit->GetEnergy();
		(*data).time = hit->GetTime();
		G4ThreeVector pos = hit->GetPosition();
		(*data).x = pos.x();
		(*data).y = pos.y();
		(*data).z = pos.z();
		branch->Fill();
	}

	if(pionNumber == 2) tree->Write();
	delete data;
}
